﻿using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Text;
using SS.Net.AppGen.Models;
using SS.Common.DBBuilder.DBDataStructure;
using SS.Common.Logging;

namespace SS.Net.AppGen.WebGenerators.WebViewGenerator
{
    /// <summary>
    /// The algorithm to generate the list view items for common table
    /// </summary>
    [Export(typeof(InsertViewItemByCommonAlgorithm))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class InsertViewItemByCommonAlgorithm : BaseInsertViewItemAlgorithm
    {
        /// <summary>
        /// The logger instance
        /// </summary>
        private readonly ILogger Logger = LoggerManager.GetLogger(typeof(InsertViewItemByCommonAlgorithm).Name);

        /// <summary>
        /// The default constructor
        /// </summary>
        public InsertViewItemByCommonAlgorithm()
        {
            this.XMLTemplate = "PartialInsertViewItemByCommon.xml";
            this.DeserializeTemplate();
        }

        /// <summary>
        /// Generate the contents of list view items
        /// </summary>
        /// <param name="tbl"></param>
        public override void GenerateContents(Table tbl)
        {
            this.Logger.InfoFormat("Generate InsertView[{0}] --> Start", tbl.Name);

            try
            {
                var contents = new StringBuilder(BaseConsts.MAX_BYTES);
                var htmlContents = this.ViewComponents.HtmlContent.Replace(BaseConsts.ConstTable, tbl.Name)
                    .Replace(BaseConsts.ConstGlobalNameSpace, WebConfiguration.Instance.NameSpace)
                    .Replace(AbstractBaseConsts.ConstScriptValidation, this.BuildScriptValidation(tbl))
                    .Replace(AbstractBaseConsts.ConstTableFields, this.BuildTableFields(tbl));

                contents.AppendLine(htmlContents);

                // Init path
                this.DirPath = Path.Combine(this.GetAppPath(), "WebGenerator", "Views", tbl.Name + "Manager");
                this.InitializeDir(this.DirPath, false);
                // Save contents to a file
                this.SaveFile(contents.ToString().TrimStart(), "_PartialInsert.cshtml");
            }
            catch (Exception ex)
            {
                this.Logger.ErrorFormat("GenerateContents Error: {0}", ex.ToString());
                throw new Exception(ex.ToString());
            }
            
            this.Logger.InfoFormat("Generate InsertView[{0}] <-- End", tbl.Name);
        }

        /// <summary>
        /// Build script for validation user inputs
        /// </summary>
        /// <param name="tbl"></param>
        /// <returns></returns>
        private string BuildScriptValidation(Table tbl)
        {
            var contents = new StringBuilder(BaseConsts.MAX_BYTES);
            var firstAtt = true;

            foreach (SS.Common.DBBuilder.DBDataStructure.Attribute attr in tbl.Attributes)
            {
                if (!attr.IsPrimaryKey)
                {
                    if (firstAtt)
                    {
                        firstAtt = false;
                        contents.AppendLine(string.Format("var {0} = $(\"#{1}\");",
                                                          attr.Name.ToLower(), attr.Name));
                    }
                    else
                    {
                        contents.Append(BaseConsts.TAB2).AppendLine(
                            string.Format("var {0} = $(\"#{1}\");", attr.Name.ToLower(), attr.Name));
                    }

                    contents.Append(BaseConsts.TAB2).AppendLine(string.Format("if ({0}.val() == \"\") {{", attr.Name.ToLower()));
                    contents.Append(BaseConsts.TAB3).AppendLine(
                        string.Format("app.logger.error('The input {0} is empty');", attr.Name));
                    contents.Append(BaseConsts.TAB3).AppendLine(
                        string.Format("$(\"#{0}\").focus();", attr.Name));
                    contents.Append(BaseConsts.TAB3).AppendLine("return false;");
                    contents.Append(BaseConsts.TAB2).AppendLine("}");
                }
            }

            return contents.ToString();
        }

        /// <summary>
        /// Generate the fields of table
        /// </summary>
        /// <param name="tbl"></param>
        /// <returns></returns>
        private string BuildTableFields(Table tbl)
        {
            var contents = new StringBuilder(BaseConsts.MAX_BYTES);
            var firstAtt = true;

            foreach (SS.Common.DBBuilder.DBDataStructure.Attribute attr in tbl.Attributes)
            {
                if (!attr.IsPrimaryKey)
                {
                    if (firstAtt)
                    {
                        firstAtt = false;
                        contents.AppendLine("<tr>");
                    }
                    else
                    {
                        contents.Append(BaseConsts.TAB5).AppendLine("<tr>");
                    }

                    contents.Append(BaseConsts.TAB6).AppendLine("<th valign=\"top\" style=\"padding-top: 2px;\">");
                    contents.Append(BaseConsts.TAB7).AppendLine(string.Format("{0}:", attr.Name));
                    contents.Append(BaseConsts.TAB6).AppendLine("</th>");
                    contents.Append(BaseConsts.TAB6).AppendLine("<td>");
                    contents.Append(BaseConsts.TAB7).AppendLine(
                        string.Format("<input type=\"text\" name=\"{0}\" id=\"{1}\" class=\"inp-form\" />", attr.Name, attr.Name));
                    contents.Append(BaseConsts.TAB6).AppendLine("</td>");
                    contents.Append(BaseConsts.TAB6).AppendLine("<td>");
                    contents.Append(BaseConsts.TAB6).AppendLine("</td>");
                    contents.Append(BaseConsts.TAB5).AppendLine("</tr>");
                }
            }

            return contents.ToString();
        }
    }
}
